<template>
  <page class="modify">
    <page-header>
      <x-header :left-options="{backText: ''}">修改密码</x-header>
    </page-header>
    <page-content :scroll="false">
      <div class="pass">
        <div class="pass-c">
          <mt-field label="原密码" placeholder="请输入原密码" type="password" v-model="oldPassword"></mt-field>
          <mt-field label="新密码" placeholder="组合字母，数字或符号" type="password" v-model="password"></mt-field>
          <mt-field label="确认密码" placeholder="再次输入新密码" type="password" v-model="refPassword"></mt-field>
        </div>
      </div>
    </page-content>
    <page-footer>
      <mt-button type="primary" size='large' class='prese' @click='prese()'>保存</mt-button>
    </page-footer>
  </page>
</template>

<script>
import { mapGetters } from 'vuex'
import { MessageBox } from 'mint-ui'
import { XHeader } from 'vux'
import { com } from '@service'
import validate from '@utils/validate'

export default {
  name: 'Modify',
  components: {
    XHeader
  },
  computed: {
    ...mapGetters({
      userInfo: 'user/info',
      token: 'user/token'
    }),
    userId () {
      return this.userInfo.id
    }
  },
  data () {
    return {
      oldPassword: '',
      password: '',
      refPassword: ''
    }
  },
  methods: {
    async prese () {
      if (!this.oldPassword) {
        MessageBox.alert('请输入原密码')
        return
      }
      if (!this.password) {
        MessageBox.alert('请输入新密码')
        return
      }
      if (this.oldPassword === this.password) {
        MessageBox.alert('新密码不能和原密码相同')
        return
      }
      if (!validate.validatPassword(this.password)) {
        MessageBox.alert('密码中必须包含字母、数字、特称字符，至少6个字符')
        return
      }
      if (!this.refPassword) {
        MessageBox.alert('请确认密码')
        return
      }
      if (this.password !== this.refPassword) {
        MessageBox.alert('两次输入密码不一致')
        return
      }
      let userId = this.userId
      let token = this.token
      let resetType = 2
      let oldPassword = this.oldPassword
      let password = this.password
      let refPassword = this.refPassword

      try {
        await com.reset({
          userId,
          token,
          resetType,
          oldPassword,
          password,
          refPassword
        })
        MessageBox.alert('请您重新登录', '提示').then((aciton) => {
          var router = this.$router
          router.push('sign')
        })
      } catch (error) {
        console.log(error)
        MessageBox.alert(error.info, '提示')
      }
    },
    reset () {
      this.oldPassword = ''
      this.password = ''
      this.refPassword = ''
    }
  },
  beforeRouteLeave (to, from, next) {
    this.reset()
    next()
  }
}
</script>

<style lang="scss" scoped>
.modify {
  height: 100%;
  width: 100%;

  mt-field label {
    margin-left: 0.5rem;
  }
  .prese {
    position: fixed;
    bottom: 0;
    background: #1e82d2;
  }
  .head {
    width: 100%;
    background: #1e82d2;
    font-size: 1.125rem;
    height: 3rem;
  }
}
</style>
